/* 8. 删除读者 */

const CHECK = require("../myUtil/formatCheck");
const db = require("../../coSqlite3");
const HTM = require("../myUtil/lib").html;

exports.deleteUser = function* (req, res) {
    console.log("----------------------8. 删除读者\n");
    let rID = req.body.rID;

    let htm = '';
    if (rID == "") {
        htm = HTM.divBegin + 1 + HTM.divEnd;
      return HTM.begin + htm + "证号不存在" + HTM.end;
    } else if (rID.length > 8) {
        htm = HTM.divBegin + 2 + HTM.divEnd;
      return HTM.begin + htm + "提交的参数有误: 证号长度不能超过8" + HTM.end;
    }

    try {
        let rows = yield db.execSQL("SELECT count(rid) as count FROM reader WHERE rid = ?", [rID]);
        if (rows[0].count == 0) {
            htm = HTM.divBegin + 1 + HTM.divEnd;
            return HTM.begin + htm + "该证号不存在" + HTM.end;
        }

        let result = yield db.execSQL("SELECt count(rid) as count FROM process where returned = 0 and rid = ?", [rID]);
        if (result[0].count != 0) {
            htm = HTM.divBegin + 2 + HTM.divEnd;
            return HTM.begin + htm + "该读者还有书未归还" + HTM.end;
        }

        // yield db.execSQL("PRAGMA foreign_keys = 1");
        yield db.execSQL("DELETE FROM reader WHERE rid = ?", [rID]);
    } catch (error) {
        htm = HTM.divBegin + 3 + HTM.divEnd + "数据库执行失败: ";
        return HTM.begin + htm + error + HTM.end;
    }
    
    htm = HTM.divBegin + 0 + HTM.divEnd;
    return HTM.begin + htm + "删除成功" + HTM.end;
}
